from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import joinedload

from src.application.server.enums import ServerStatus
from src.infrastructure.db.models import Order, User, VPNServer


async def get_free_vpn_server(session: AsyncSession, user: User) -> list[VPNServer]:
    q = (
        select(VPNServer)
        .filter(VPNServer.status == ServerStatus.active)
        .outerjoin(VPNServer.orders)
        .filter(Order.user != user)
    ).options(joinedload(VPNServer.orders))

    res = await session.execute(q)

    servers = res.scalars().unique().all()

    return [server for server in servers if len(server.orders) < 5]
